package cn.ekgc.bmdsad.day13;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SS {
    static String msg;

    public static void main(String[] args) {
        try (ServerSocket ss = new ServerSocket ( 8080 )) {
            while (true) {
                Socket c = ss.accept ();
                String ip = c.getInetAddress ().getHostAddress ();
                System.out.println ( "连接到聊天室" );
                new Thread ( () -> {
//读
                    try {
                        BufferedReader in = new BufferedReader ( new InputStreamReader ( c.getInputStream () ) );
                        while (true) {
                            String line = in.readLine ();
                            synchronized ("a") {
                                msg = ip + "说" + line;
                                "a".notifyAll ();
                            }
                        }
                    } catch (IOException e) {
                        // e.printStackTrace ();
                        System.out.println ( ip + "退出聊天室" );
                    }

                } ).start ();

                new Thread ( () -> {
//写
                    try {
                        PrintWriter out = new PrintWriter ( c.getOutputStream () );
                        while (true) {
                            synchronized ("a") {
                                "a".wait ();

                                out.println ( msg );
                                out.flush ();
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace ();
                    } catch (InterruptedException e) {
                        e.printStackTrace ();
                    }
                } ).start ();
            }

        } catch (IOException e) {
            e.printStackTrace ();
        }
    }
}
